package org.wat.wcy.isi.mmazur.bp.io.xpdl.processors;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.wat.wcy.isi.mmazur.bp.io.model.IdDesc;
import org.wat.wcy.isi.mmazur.bp.io.model.Node;
import org.wat.wcy.isi.mmazur.bp.io.model.GraphicsInfo;
import org.wat.wcy.isi.mmazur.bp.io.model.Transition;
import org.wat.wcy.isi.mmazur.bp.io.model.enums.NodeType;
import org.wat.wcy.isi.mmazur.bp.io.model.temporary.Route;
import org.wat.wcy.isi.mmazur.bp.io.xpdl.IXMLProcessor;
import org.xml.sax.Attributes;

public class PoolsProcessor implements IXMLProcessor {

	private Node currentNode;
	private Map<String, Node> nodes;
	
	public PoolsProcessor() {
		nodes = new HashMap<String, Node> ();
	}
	
	@Override
	public void startElement(String name, Attributes attr) {
		if (StringUtils.equals(name, "/Package/Pools/Pool")) {
			boolean boundaryVisible = StringUtils.equalsIgnoreCase(attr.getValue("BoundaryVisible"), "true");
			if (boundaryVisible) {
				currentNode = new Node();
				currentNode.setType(NodeType.POOL);
				String id = attr.getValue("Id");
				currentNode.setId(new IdDesc(id));
				currentNode.setName(attr.getValue("Name"));
				nodes.put(id, currentNode);
			}
		} else if (StringUtils.equals(name, "/Package/Pools/Pool/Lanes/Lane")) {
			currentNode = new Node();
			currentNode.setType(NodeType.LANE);
			String id = attr.getValue("Id");
			String parentPool = attr.getValue("ParentPool");
			currentNode.setId(new IdDesc(id));
			currentNode.setName(attr.getValue("Name"));
			Node parent = new Node();
			parent.setId(new IdDesc(parentPool));
			currentNode.setParent(parent);
		} else if (name.matches("/Package/Pools/Pool/(Lanes/Lane/){0,1}NodeGraphicsInfos/NodeGraphicsInfo")) {
			if (currentNode == null) {
				return;
			}
			int height = Integer.parseInt(attr.getValue("Height"));
			int width = Integer.parseInt(attr.getValue("Width"));
			currentNode.setGraphicsInfo(new GraphicsInfo(0,0,width, height));
		} else if (name.matches("/Package/Pools/Pool/(Lanes/Lane/){0,1}NodeGraphicsInfos/NodeGraphicsInfo/Coordinates")) {
			if (currentNode == null) {
				return;
			}
			int x = Integer.parseInt(attr.getValue("XCoordinate"));
			int y = Integer.parseInt(attr.getValue("YCoordinate"));
			currentNode.getGraphicsInfo().setX(x);
			currentNode.getGraphicsInfo().setY(y);
		}
	}

	@Override
	public void endElement(String name, String characters) {
		if (StringUtils.equals(name, "/Package/Pools/Pool/Lanes/Lane")) {
			String id = currentNode.getId().toString();
			nodes.put(id, currentNode);
		}
	}

	@Override
	public Map<String, Node> getNodes() {
		return null;
	}

	@Override
	public Map<Route, Transition> getTransitions() {
		return null;
	}

	@Override
	public Map<String, Node> getPools() {
		return nodes;
	}
}